package net.zjitc.dao.impl;

import net.zjitc.dao.UserDao;
import net.zjitc.domain.user;
import net.zjitc.service.UserService;
import net.zjitc.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @Author admin
 * @Date 2019/3/4 10:06
 */
public class UserDaoImpl implements UserDao {
    @Override
    public user login(String username, String password) {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where username=? and password=?";
        user user = null;
        try {
             user = queryRunner.query(sql, new BeanHandler<user>(user.class), username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public user register(String username) {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where username = ?";
        user user = null;
        try {
            user = queryRunner.query(sql,new BeanHandler<user>(user.class),username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public void register_add(String username, String password) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "insert into user(username,password)values(?,?)";
        queryRunner.update(sql,new Object[]{username,password});
    }

    @Override
    public user findByID(int uid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from user where uid=?";
        user user = queryRunner.query(sql, new BeanHandler<user>(user.class), uid);
        return user;
    }

    @Override
    public void center_edit(user user, String uid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "update user set username=?,password=?,sex=?,phone=?,address=? where uid =?";
        queryRunner.update(sql,new Object[]{user.getUsername(),user.getPassword(),user.getSex(),user.getPhone(),user.getAddress(),uid});
    }
}
